import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '@/layout/index.vue'

Vue.use(VueRouter)

const publicRoutes = [
  {
    path: '/',
    name: 'home',
    component: layout,
    redirect: '/resource',
    children: [
      {
        path: 'resource',
        component: () => import('@/views/resource/index.vue')
      },
      {
        path: 'resourceAdd',
        component: () => import('@/views/resource/add.vue')
      },
      {
        path: 'config',
        component: () => import('@/views/config/index.vue')
      },
      {
        path: 'message',
        component: () => import('@/views/message/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: publicRoutes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') next()
    else next('/login')
  }
})

export default router
